package com.issac.service.serviceImpl;

import com.issac.common.R;
import com.issac.entity.User;
import com.issac.mapper.UserMapper;
import com.issac.service.AccountService;
import com.issac.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * @ClassName LoginService
 * @Author zy
 * @Date 2021/10/27 20:34
 * @Description LoginService
 * @Version 1.0
 */
@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 登录
     * @param account
     * @return
     */
    public R doLogin(User account) {
        // 验证密码
        String accountId = account.getAccountId();
        String password = account.getPassword();
        // 对用户输入的密码进行加密
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());

        User user = userMapper.selectById(accountId);

        // 验证id以及对加密之后的密码与数据库中已经加密的密码对比
        if (accountId.equals(user.getAccountId()) && md5Password.equals(user.getPassword())){
            // 验证成功生成token返回至前端
            String s = JwtUtils.generateToken(accountId);
            R ok = R.ok(s);
            return ok;
        }

        // 验证失败
        R error = R.error("账号密码错误");
        return error;
    }

    /**
     * 注册
     * @param user
     * @return
     */
    public R register(User user) {
        int insert = 0;
        try {
            // md5加密后存入数据库
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
            insert = userMapper.insert(user);
            return R.ok(insert);
        } catch (Exception e) {
            return R.error(insert);
        }
    }
}
